angular.module('starter.services', ['starter', 'ionic', 'ngCordova', 'starter.spmsLookupService'])

  .factory('$dfUtil', function ($http, $q, $dfHttp, $loading) {
    function subDate(dateStr) {
      return dateStr.substring(0, dateStr.indexOf(" "));
    }

    function trimStr(str) {
      return str.replace(/(^\s*)|(\s*$)/g,"");
    }

    function isEmptyObject(e) {
      var t;
      for (t in e)
        return !1;
      return !0
    }

    function convertDateToString(date) {
      if (!angular.isDate(date)) {
        date = new Date();
      }
      return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    }

    function convertStringToDate(string) {
      if (!angular.isString(string)) {
        return new Date();
      }
      string = string.replace(/-/g, "/");
      var date = new Date(string);

      return date;
    }

    function replaceOfEmpty (string) {
      if (string === "" || typeof string === "undefined"){
        return 0;
      }else {
        return string;
      }
    }

    function convertGpsToBaiduGps(arrays) {

      var deferred = $q.defer();
      var promise = deferred.promise;

      if (!angular.isArray(arrays)) {
        deferred.resolve([]);
      } else {
        var url = "http://api.map.baidu.com/geoconv/v2/";
        var params = {
          coords: ""
        };
        angular.forEach(arrays, function (gps) {
          params.coords += gps;
        });
        params.coords = params.coords.substr(0, params.coords.length - 1);
        params.ak = "Lu5gxGyIKnVtLI2b2RjD2s43jktRG8ok"
        params.from = "1";
        params.to = "5";

        $dfHttp.getWithoutENV(url, params).success(function (data) {
          if (data.status == 0) {
            deferred.resolve(data.result);
          }
        }).error(function (data) {
          $loading.showError("定位失败")
        });
      }

      promise.success = function (fn) {
        promise.then(fn);
        return promise;
      }

      return promise;
    }

    function changecss(theClass, element, value) {
      var cssRules;
      if (document.all) {
        cssRules = 'rules';
      } else if (document.getElementById) {
        cssRules = 'cssRules';
      }
      for (var S = 0; S < document.styleSheets.length; S++) {
        for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
          if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
            document.styleSheets[S][cssRules][R].style[element] = value;
          }
        }
      }
    }

    function arrayBufferToBase64(buffer) {
      var binary = '';
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
      }
      return window.btoa(binary);
    }

    function loadJs(id,fileUrl) {
      var scriptTag = document.getElementById(id);
      var oHead = document.getElementsByTagName('BODY')[0];
      var oScript= document.createElement("script");
      if (scriptTag) oHead.removeChild(scriptTag);
      oScript.id = id;
      oScript.type = "text/javascript";
      oScript.src=fileUrl ;
      oHead.appendChild( oScript);
    }

    return {
      subDate: subDate,
      trimStr: trimStr,
      isEmptyObject: isEmptyObject,
      convertDateToString: convertDateToString,
      convertStringToDate: convertStringToDate,
      convertGpsToBaiduGps: convertGpsToBaiduGps,
      changecss:changecss,
      arrayBufferToBase64:arrayBufferToBase64,
      loadJs:loadJs,
      replaceOfEmpty : replaceOfEmpty
    }
  })

  //图片选择
  .factory('$dfImagePicker', function ($q, $ionicActionSheet, $cordovaCamera) {
    return {
      getImageList: function (paramOptions) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        //移除.platform-android 样式,来让actionsheet样式好看
        var cancelActionSheet = $ionicActionSheet.show({
          buttons: [{text: '相机'}, {text: '图库'}],
          cancelText: '关闭',
          cancel: function () {
            return true;
          },
          buttonClicked: function (index) {
            cancelActionSheet();
            switch (index) {
              case 0:
                var options = {
                  quality: 80,
                  destinationType: Camera.DestinationType.FILE_URI,
                  sourceType: Camera.PictureSourceType.CAMERA,
                  allowEdit: false,
                  encodingType: Camera.EncodingType.JPEG,
                  targetWidth: 1200,
                  targetHeight: 1200,
                  popoverOptions: CameraPopoverOptions,
                  saveToPhotoAlbum: false,
                  correctOrientation: true
                };

                $cordovaCamera.getPicture(options).then(function (fileUrl) {
                  var imageUrlArr = new Array();
                  imageUrlArr[0] = fileUrl;
                  deferred.resolve(imageUrlArr)
                }, function (err) {
                  deferred.reject(err);
                });

                break;
              case 1:
                options = paramOptions || {}

                options.minImages = options.minImages || 0
                options.maxImages = options.maxImages || 9
                options.mediaType = options.mediaType || 'any'
                options.width = options.width || 1200
                options.height = options.height || 1200
                options.quality = options.quality || 80

                window.plugins.imagePicker.getPictures(function (results) {

                  deferred.resolve(results);
                }, function (error) {
                  deferred.reject(error);
                }, options);
                break;
            }
          }
        })

        promise.success = function (fn) {
          promise.then(fn);
          return promise;
        }

        promise.error = function (fn) {
          promise.then(null, fn);
          return promise;
        }

        return promise;
      }
    }
  })

  //网络请求通用库
  .factory('$dfHttp', function ($q, $http, ENV) {
    return {
      get: function (url, params, headers) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        var paramStr = "?";
        for (var key in params) {
          paramStr = paramStr + key + "=" + encodeURI(params[key]) + "&";
        }
        //拼接完整的url
        var fullUrl = encodeURI(ENV.api + url);
        fullUrl += paramStr;

        $http.get(fullUrl, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'timeout': 10000
          },
        }).success(function (data, status, config, header) {
            if(!data){
              data = {};
            }
            data.options = params ;
            deferred.resolve(data);
            //$loading.showSuccess("登录成功");
          })
          .error(function (data, status, config, header) {
            if(!data) {
              data = {};
            }
            data.options = params ;
            deferred.reject(data);
          });

        promise.success = function (fn) {
          promise.then(fn);
          return promise;
        }

        promise.error = function (fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },

      getWithoutENV: function (url, params, headers) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        var paramStr = "?";
        for (var key in params) {
          paramStr = paramStr + key + "=" + encodeURI(params[key]) + "&";
        }
        //拼接完整的url
        var fullUrl = url;
        fullUrl += paramStr;

        $http.get(fullUrl, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          },
        }).success(function (data, status, config, header) {
            ////console.log(data);
            if(!data){
              data = {};
            }
            data.options = params ;
            deferred.resolve(data);
            //$loading.showSuccess("登录成功");
          })
          .error(function (data, status, config, header) {
            if(!data){
              data = {};
            }
            data.options = params ;
            deferred.reject(data);
          });

        promise.success = function (fn) {
          promise.then(fn);
          return promise;
        }

        promise.error = function (fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },

      post: function (url, params, headers) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        //拼接完整的url
        var fullUrl = encodeURI(ENV.api + url);

        $http.post(fullUrl, params, {
          headers: {'Content-Type': 'application/json; charset=UTF-8'}
        }).success(function (data, status, config, header) {
            if(!data){
              data = {};
            }
            data.options = params ;
            deferred.resolve(data);
            //$loading.showSuccess("登录成功");
          })
          .error(function (data, status, config, header) {
            if(!data){
              data = {};
            }
            data.options = params ;
            deferred.reject(data);
          });

        promise.success = function (fn) {
          promise.then(fn);
          return promise;
        }

        promise.error = function (fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },

      postForm: function (url, params, files, headers) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        //拼接完整的url
        var fullUrl = encodeURI(ENV.api + url);

        var fd = new FormData();
        fd.append('datas', JSON.stringify(params));

        if(files && files.length > 0) {
          angular.forEach(files, function (file) {
            fd.append('imageFiles', file);
          })
        }else{
          fd.append('imageFiles',[]);
        }

        $http({
          method: 'POST',
          url: fullUrl,
          data: fd,
          headers: {'Content-Type': undefined},
          transformRequest: angular.identity
        }).success(function (data, status, config, header) {
            deferred.resolve(data);
            //$loading.showSuccess("登录成功");
          })
          .error(function (data, status, config, header) {
            deferred.reject(data);
          });

        promise.success = function (fn) {
          promise.then(fn);
          return promise;
        }

        promise.error = function (fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      }
    }
  })

  //加载动画
  .factory('$loading', function ($ionicLoading, $timeout) {

    return {
      show: function (content) {
        $ionicLoading.show({
          template: '<devin-loading spinner="lines" content="' + content + '"></devin-loading>',
          content: content,
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 600,
          showDelay: 0
        });
      },
      showSuccess: function (content) {
        $ionicLoading.hide();
        if (!content) {
          content = '服务器出了一点小问题,请稍后再试';
        }
        $ionicLoading.show({
          template: '<devin-loading-over spinner="ion-checkmark-round" content="' + content + '"></devin-loading-over>',
          content: content,
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 600,
          showDelay: 1
        });
        $timeout(function () {
          $ionicLoading.hide();
        }, 1300);
      },
      showError: function (content) {
        $ionicLoading.hide();
        if (!content) {
          content = '服务器出了一点小问题,请稍后再试';
        }
        $ionicLoading.show({
          template: '<devin-loading-over spinner="ion-close-round" content="' + content + '"></devin-loading-over>',
          content: content,
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 600,
          showDelay: 1
        });
        $timeout(function () {
          $ionicLoading.hide();
        }, 1400);
      },
      hide: function () {
        $ionicLoading.hide();
      }
    }
  })

  .factory('$dfBoradcast', function ($rootScope) {

    //var $currentScope ;
    //
    //return {
    //  sendBoradcast : function(key,data,$scope){
    //    if($scope) {
    //      $scope.$parent.$emit(key,data);
    //      $scope.$parent.$broadcast(key,data);
    //      $scope.$parent.$parent.$emit(key,data);
    //      $scope.$parent.$parent.$broadcast(key,data);
    //    }else {
    //      $rootScope.$broadcast(key);
    //    }
    //  }
    //}

    return {
      sendBoradcast: function (key, data) {
        $rootScope['' + key + ''] = data;
        $rootScope.$watch('' + key + '', function () {
          var value = $rootScope['' + key + ''];
          $rootScope['' + key + '-fn'](value);
          $rootScope['' + key + ''] = {};
        });
      },
      //function(data){}
      getBoradcast: function (key, fn) {
        $rootScope['' + key + '-fn'] = fn;
      },
      sendBoradcastOnce: function (key, value) {
        $rootScope['' + key + '-fn'](value);
      },
      clearBoradcast: function (key) {
        $rootScope['' + key + '-fn'] = undefined;
      }
    }
  })

  .factory('$dfDB', function ($q, Loki, $timeout, $ionicPlatform, $dfUtil) {
    var _db;
    var _spmsLookupDB ;
    var _spmsRegionDB ;
    var userCollection;

    var saveRequest = 0;
    function initDB() {
      if ($dfUtil.isEmptyObject(ionic.Platform.device())) {
        //var adapter = new LokiIndexedAdapter("spms-loki");
        _db = new Loki('spmsDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          autoload: true,
          autoloadCallback: function (e) {
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _db.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- loki");
          },1000);
        });

        _spmsRegionDB = new Loki('_spmsRegionDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          autoload: true,
          autoloadCallback: function (e) {
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _spmsRegionDB.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- loki");
          },1000);
        });

        _spmsLookupDB = new Loki('_spmsLookupDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          autoload: true,
          autoloadCallback: function (e) {
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _spmsLookupDB.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- loki");
          },1000);
        });

        //_userDb = new Loki('spmsUserDB',{
        //  autosave:true,
        //  autosaveInterval: 1000 // 1 second
        //});
      } else {
        var adapter = new LokiCordovaFSAdapter({"prefix": "spms-loki"});
        _db = new Loki('spmsLokiDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          databaseVersion:1.2,
          adapter: adapter,
          autoload: true,
          autoloadCallback: function (e) {
            //userCollection = _db.getCollection(collectionName);
            if (!_db) {
              _db.loadDatabase();
            }
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _db.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- LokiCordovaFSAdapter");
          },1000);
        });

        _spmsRegionDB = new Loki('_spmsRegionDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          databaseVersion:1.2,
          adapter: adapter,
          autoload: true,
          autoloadCallback: function (e) {
            //userCollection = _db.getCollection(collectionName);
            if (!_spmsRegionDB) {
              _spmsRegionDB.loadDatabase();
            }
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _spmsRegionDB.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- LokiCordovaFSAdapter");
          },1000);
        });

        _spmsLookupDB = new Loki('_spmsLookupDB', {
          autosave: true,
          autosaveInterval: 10000, // 1 second
          databaseVersion:1.2,
          adapter: adapter,
          autoload: true,
          autoloadCallback: function (e) {
            //userCollection = _db.getCollection(collectionName);
            if (!_spmsLookupDB) {
              _spmsLookupDB.loadDatabase();
            }
          },
          autosaveCallback:function(e){
            console.log('autoSave:' +e);
          }
        });
        _spmsLookupDB.loadDatabase(function(){
          $timeout(function(){
            console.log("logger -------- LokiCordovaFSAdapter");
          },1000);
        });
        //_userDb = new Loki('spmsUserDB',{
        //  autosave:true,
        //  autosaveInterval: 1000 // 1 second
        //});
      }
    }

    return {
      collectionDB: function (collectionName) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        var options = {};
        var collection;
        //if(!_db){
        //$timeout(function(){
        //  _db.loadDatabase(options, function (content) {
        //    //console.log(content);
        collection = _db.getCollection(collectionName);

        if (!collection) {
          collection = _db.addCollection(collectionName);
        }
        deferred.resolve(collection);

        promise.collectionSuccess = function (fn) {
          promise.then(fn);
          return promise;
        }
        return promise;
      },
      collectionLookupDB: function (collectionName) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        var options = {};
        var collection;
        //if(!_db){
        //$timeout(function(){
        //  _db.loadDatabase(options, function (content) {
        //    //console.log(content);
        collection = _spmsLookupDB.getCollection(collectionName);

        if (!collection) {
          collection = _spmsLookupDB.addCollection(collectionName);
        }
        deferred.resolve(collection);

        promise.collectionSuccess = function (fn) {
          promise.then(fn);
          return promise;
        }
        return promise;
      },
      initDB: initDB,
      dbSave: function () {
             _db.save(function (data) {
               console.log('saveSuccess:' +data);
             });
      },
      lookupDBSave:function (){

      },
      regionDBSave:function() {

      },
      collectionDBSync: function (collectionName) {
        var collection;

        var options = {};

        if(!_db){
          return ;
        }
        collection = _db.getCollection(collectionName);
        //console.log(collection + ":coll");
        //});

        if (!collection) {
          collection = _db.addCollection(collectionName);
        }

        return collection;
        //,350);
      },
      collectionLookupDBSync: function (collectionName) {
        var collection;

        var options = {};

        if(!_spmsLookupDB){
          return ;
        }
        collection = _spmsLookupDB.getCollection(collectionName);
        //console.log(collection + ":coll");
        //});

        if (!collection) {
          collection = _spmsLookupDB.addCollection(collectionName);
        }

        return collection;
        //,350);
      },
      collectionRegionDBSync:  function (collectionName) {
        var collection;

        var options = {};

        if(!_spmsRegionDB){
          return ;
        }
        collection = _spmsRegionDB.getCollection(collectionName);
        //console.log(collection + ":coll");
        //});

        if (!collection) {
          collection = _spmsRegionDB.addCollection(collectionName);
        }

        return collection;
        //,350);
      },

      //collectionLookupDB:function(collectionName){
      //  var deferred = $q.defer();
      //  var promise = deferred.promise;
      //
      //  var options = {};
      //    var collection ;
      //    //console.log(_lookupDb);
      //  _lookupDb.loadDatabase(options, function () {
      //      collection = _lookupDb.getCollection(collectionName);
      //
      //      if (!collection) {
      //        collection = _lookupDb.addCollection(collectionName);
      //      }
      //      deferred.resolve(collection);
      //    });
      //    promise.collectionSuccess = function(fn) {
      //      promise.then(fn);
      //      return promise ;
      //    }
      //  return promise;
      //},
      //collectionUserDB:function(collectionName){
      //  var deferred = $q.defer();
      //  var promise = deferred.promise;
      //
      //  var options = {};
      //  var collection ;
      //  //console.log(_userDb);
      //  _userDb.loadDatabase(options, function () {
      //    collection = _userDb.getCollection(collectionName);
      //
      //    if (!collection) {
      //      collection = _userDb.addCollection(collectionName);
      //    }
      //    deferred.resolve(collection);
      //  });
      //  promise.collectionSuccess = function(fn) {
      //    promise.then(fn);
      //    return promise ;
      //  }
      //  return promise;
      //}
    }
  })

  .factory('$dfCityPicker', function ($ionicScrollDelegate, $log, $timeout, $ionicModal) {

    //$scope.settings = {
    //  enableFriends: true
    //};

    //var $scope = $rootScope.$new();
    //
    //$scope.executeScroll = function() {
    //  //$log.log($ionicScrollDelegate.$getByHandle('scrollOne').getScrollPosition());
    //}
    //
    //$scope.scrollProperty = {};
    //
    //$scope.scroll = {
    //  'scrollPro':[],
    //  'scrollCity':[],
    //  'scrollTow':[]
    //};
    //
    //$scope.releaseFromScrollOne = function() {
    //  var scrollOneY = $ionicScrollDelegate.$getByHandle('scrollOne').getScrollPosition().top ;
    //
    //
    //  if(scrollOneY % 54 > 27) {
    //    $ionicScrollDelegate.$getByHandle('scrollOne').scrollTo(0,scrollOneY + (53 - (scrollOneY % 53)),true);
    //    $scope.scrollProperty.scrollOneIndex = (scrollOneY + (53 - (scrollOneY % 53))) / 53 ;
    //  }else {
    //    $ionicScrollDelegate.$getByHandle('scrollOne').scrollTo(0,scrollOneY - (scrollOneY % 53),true);
    //    $scope.scrollProperty.scrollOneIndex = (scrollOneY - (scrollOneY % 53)) / 53 ;
    //  }
    //
    //
    //  //console.log($scope.scrollProperty.scrollOneIndex + ":" +$scope.pros[$scope.scrollProperty.scrollOneIndex]);
    //  $scope.scrollProperty.scrollTowArray = $scope.pros[$scope.scrollProperty.scrollOneIndex].next ;
    //  $scope.scrollProperty.scrollThreeArray = $scope.pros[$scope.scrollProperty.scrollOneIndex].next[0].next ;
    //
    //  $ionicScrollDelegate.$getByHandle('scrollTwo').scrollTop();
    //  $ionicScrollDelegate.$getByHandle('scrollThree').scrollTop();
    //
    //  //$log.log(scrollOneY);
    //}
    //
    //$scope.releaseFromScrollTwo = function() {
    //  var scrollTwoY = $ionicScrollDelegate.$getByHandle('scrollTwo').getScrollPosition().top ;
    //
    //  if(scrollTwoY % 54 > 27) {
    //    $ionicScrollDelegate.$getByHandle('scrollTwo').scrollTo(0,scrollTwoY + (53 - (scrollTwoY % 53)),true);
    //    $scope.scrollProperty.scrollTwoIndex = (scrollTwoY + (53 - (scrollTwoY % 53))) / 53 ;
    //  }else {
    //    $ionicScrollDelegate.$getByHandle('scrollTwo').scrollTo(0,scrollTwoY - (scrollTwoY % 53),true);
    //    $scope.scrollProperty.scrollTwoIndex = (scrollTwoY - (scrollTwoY % 53)) / 3 ;
    //  }
    //
    //  $ionicScrollDelegate.$getByHandle('scrollThree').scrollTop();
    //  $scope.scrollProperty.scrollThreeArray = $scope.pros[$scope.scrollProperty.scrollOneIndex].next[$scope.scrollProperty.scrollTwoIndex].next ;
    //  //$log.log(scrollOneY);
    //}
    //
    //$scope.releaseFromScrollThree = function() {
    //  var scrollThreeY = $ionicScrollDelegate.$getByHandle('scrollThree').getScrollPosition().top ;
    //
    //  if(scrollThreeY % 54 > 27) {
    //    $ionicScrollDelegate.$getByHandle('scrollThree').scrollTo(0,scrollThreeY + (53 - (scrollThreeY % 53)),true);
    //    $scope.scrollProperty.scrollTwoIndex = (scrollThreeY + (53 - (scrollThreeY % 53))) / 53 ;
    //  }else {
    //    $ionicScrollDelegate.$getByHandle('scrollThree').scrollTo(0,scrollThreeY - (scrollThreeY % 53),true);
    //    $scope.scrollProperty.scrollTwoIndex = (scrollThreeY - (scrollThreeY % 53)) / 53 ;
    //  }
    //  //$log.log(scrollOneY);
    //}
    //
    //
    //$scope.pros = [{
    //  'code':'beijing',
    //  'name':'北京',
    //  'next':[{
    //    'code':'beijing1',
    //    'name':'北京1',
    //    'next':[{
    //      'code':'beijing11',
    //      'name':'北京11'
    //    },{
    //      'code':'beijing12',
    //      'name':'北京12'
    //    },{
    //      'code':'beijing13',
    //      'name':'北京13'
    //    },{
    //      'code':'beijing14',
    //      'name':'北京14'
    //    },{
    //      'code':'beijing15',
    //      'name':'北京15'
    //    }]
    //  },{
    //    'code':'beijing2',
    //    'name':'北京2',
    //    'next':[{
    //      'code':'beijing21',
    //      'name':'北京21'
    //    },{
    //      'code':'beijing22',
    //      'name':'北京22'
    //    },{
    //      'code':'beijing23',
    //      'name':'北京23'
    //    },{
    //      'code':'beijing24',
    //      'name':'北京24'
    //    },{
    //      'code':'beijing25',
    //      'name':'北京25'
    //    }]
    //  }]
    //},
    //  {'code':'shanghai',
    //    'name':'上海',
    //    'next':[{
    //      'code':'shanghai1',
    //      'name':'上海1',
    //      'next':[{
    //        'code':'shanghai11',
    //        'name':'上海11'
    //      },{
    //        'code':'shanghai12',
    //        'name':'上海12'
    //      },{
    //        'code':'shanghai13',
    //        'name':'上海13'
    //      },{
    //        'code':'shanghai14',
    //        'name':'上海14'
    //      },{
    //        'code':'shanghai15',
    //        'name':'上海15'
    //      }]
    //    },{
    //      'code':'shanghai2',
    //      'name':'上海2',
    //      'next':[{
    //        'code':'shanghai21',
    //        'name':'上海21'
    //      },{
    //        'code':'shanghai22',
    //        'name':'上海22'
    //      },{
    //        'code':'shanghai23',
    //        'name':'上海23'
    //      },{
    //        'code':'shanghai24',
    //        'name':'上海24'
    //      },{
    //        'code':'shanghai25',
    //        'name':'上海25'
    //      }]
    //    }]
    //  }];
    //
    ////$timeout(function(){
    ////  $scope.releaseFromScrollOne();
    ////},500);
    //
    //$ionicModal.fromTemplateUrl('#/template/city-choice.html', {
    //  scope: $scope,
    //  animation: 'slide-in-up'
    //}).then(function (modal) {
    //  $scope.modal = modal;
    //});
    //
    //$scope.$on('$destroy', function () {
    //  $scope.modal.remove();
    //});
    //
    //function openModal() {
    //  $scope.modal.show();
    //}
    //
    //function closeModal() {
    //  $scope.modal.hide();
    //}
    //
    //
    //return{
    //  showModal:function(data,callback){
    //    $scope.data = data ;
    //    $scope.callback = callback ;
    //    openModal();
    //  },
    //  hideModal:function(){
    //    closeModal();
    //  },
    //  finishModal:function(){
    //    $scope.callback($scope.data);
    //  }
    //}
  })

  .factory('Chats', function () {
    // Might use a resource here that returns a JSON array

    // Some fake testing data
    var chats = [{
      id: 0,
      name: 'Ben Sparrow',
      lastText: 'You on your way?',
      face: 'img/ben.png'
    }, {
      id: 1,
      name: 'Max Lynx',
      lastText: 'Hey, it\'s me',
      face: 'img/max.png'
    }, {
      id: 2,
      name: 'Adam Bradleyson',
      lastText: 'I should buy a boat',
      face: 'img/adam.jpg'
    }, {
      id: 3,
      name: 'Perry Governor',
      lastText: 'Look at my mukluks!',
      face: 'img/perry.png'
    }, {
      id: 4,
      name: 'Mike Harrington',
      lastText: 'This is wicked good ice cream.',
      face: 'img/mike.png'
    }];

    return {
      all: function () {
        return chats;
      },
      remove: function (chat) {
        chats.splice(chats.indexOf(chat), 1);
      },
      get: function (chatId) {
        for (var i = 0; i < chats.length; i++) {
          if (chats[i].id === parseInt(chatId)) {
            return chats[i];
          }
        }
        return null;
      }
    };
  });
